package com.ai.nsa;

import com.ai.nsa.utils.CalendarUtils;
import com.ai.nsa.utils.LeftPad;
import com.ai.nsa.utils.hbase.model.RowKey;

import java.text.ParseException;

import static com.ai.nsa.NSAConstants.*;

/**
 * @author Feng Chen 2017/7/25.
 */
public class DefaultNSATableRoute implements NSATableRoute {

    @Override
    public String getTable(String rowKey) {
        RowKey _rowkey_ = RowKeyParser.parse(rowKey);
        String tradeDate = _rowkey_.getDate();
        try {

            return LeftPad.pad(CalendarUtils.getMonth(tradeDate), 2, "0");
        } catch (ParseException e) {
            return null;
        }
    }


    ////////////////////////////////////////////////////

    private static class RowKeyParser {

        public static RowKey parse(String str) {

            if (str == null || str.length() < ROWKEY_LENGTH) {
                return null;
            }

            RowKey rowKey = new RowKey();
            int index = 0;
            String part = str.substring(index, PARTITION_LENGTH + index);
            index += PARTITION_LENGTH;

            String serialNumber = str.substring(index, SERIAL_NUMBER_LENGTH + index);
            index += SERIAL_NUMBER_LENGTH;

            String tradeDate = str.substring(index, TRADE_DATE_LENGTH + index);
            index += TRADE_DATE_LENGTH;

            String serial = str.substring(index);
            rowKey.part(part)
                    .id(serialNumber)
                    .date(tradeDate)
                    .serial(serial);

            return rowKey;
        }

    }


    public static void main(String[] args) {

        NSATableRoute tableRoute = new DefaultNSATableRoute();

        String table = tableRoute.getTable("0118900706908201707250000001");

        System.out.println(table);


    }


}
